/**
 * 
 */
package profile.aspect;

import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

/**
 * @author dtran091109
 *
 */
public class SQLExecuteContext {

	private Map<Integer, String> sqlMap = new HashMap<Integer, String>();
	
	public void addStatement(Statement stmt, String sql) {
		//System.out.println("add statement " + stmt + " : \n" + sql);
		String oldValue = sqlMap.put(stmt.hashCode(), sql);
		if (oldValue != null) {
			System.err.println("Multiple sql on same statement :\nOld: " + oldValue + "\nNew:" + sql);
		}
	}

	public void closeStatement(Statement stmt) {
		String sql = sqlMap.remove(stmt.hashCode());
		try {
			StringBuffer sqlWarnings = getWarnings(stmt.getWarnings());
			if (sqlWarnings.length() > 0) {
				sqlWarnings.append("=================================================================\n");
				sqlWarnings.insert(0, sql + " : \n");
				
				addToFile(sqlWarnings);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private StringBuffer getWarnings(SQLWarning w) throws Exception {
		//StringBuffer buffer = new StringBuffer(sqlRequest).append("\n---------------------------------------------\n");
    	StringBuffer buffer = new StringBuffer("");
		while (w != null) {
			buffer.append(w.getMessage()); //.append('\n');
			w = w.getNextWarning();
		}
		return buffer;
	}

	private static void addToFile(StringBuffer buffer) throws Exception {
		PrintWriter writer = new PrintWriter(new FileOutputStream("io.txt", true));
		writer.println(buffer.toString());
		writer.close();
	}
}
